package chattingRoom;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {
    public static void main(String[] args) throws IOException{
        ServerSocket serverSocket=new ServerSocket(8888);
        //阻塞式
        while (true) {
            Socket accept = serverSocket.accept();

            //实现多线程的功能
            new Thread(()->{
                //得到客户端传过来的信息
                DataInputStream dataInputStream = null;
                DataOutputStream dataOutputStream =null;
                try {
                    dataInputStream = new DataInputStream(accept.getInputStream());
                    dataOutputStream = new DataOutputStream(accept.getOutputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                boolean Runable=true;
                //返回消息
                while (Runable) {
                    String message = null;
                    try {
                        //得到信息
                        message = dataInputStream.readUTF();
                        //写回给客户端
                        dataOutputStream.writeUTF(message);
                        //释放资源
                        dataOutputStream.flush();
                    } catch (IOException e) {
                        Runable=false;
                    }
                }
                try {
                    dataInputStream.close();
                    dataOutputStream.close();
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }


    }

}
